package com.xszx.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

   @Override
   public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
      System.out.println("进入页面");
   }

   @Override
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      System.out.println("after");
   }

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      System.out.println("进入拦截器");


      String uri = request.getRequestURI();
      System.out.println(uri);
      if(uri.contains("login") || uri.contains("adduser")){
         System.out.println("有效操作");
         return true;
      }else {
         Object name = request.getSession().getAttribute("username");
         if(name != null){
            return true;
         }else{

            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write("<script>alert('会话信息过期，请重新登录')</script>");
            writer.write("<script>window.location.href='/jsp/login.jsp'</script>");
            writer.close();
            System.out.println("非法登录");
            return false;
         }
      }
      }




   }



